﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using DKIM;
using System.Net.Mail;

namespace ERPStore.DKIMEmailer
{
	public class EmailerService : ERPStore.Services.EmailerService
	{
		public EmailerService(ERPStore.Logging.ILogger logger)
			: base(logger)
		{

		}

		public override void Send(ERPStore.Models.MailMessage mailMessage)
		{
			Send(mailMessage, null);
		}

		public override void Send(Models.MailMessage mailMessage, DateTime? scheduledDate)
		{
			var message = (System.Net.Mail.MailMessage)mailMessage;
			Send(message);
		}

		public override void Send(MailMessage message)
		{
			AddDkimHeader(message);

			if (!message.Headers.AllKeys.Any(i => i == "X-Mailer"))
			{
				message.Headers.Add("X-Mailer", "ERPStore.DKIMEmailerService");
			}
			else
			{
				message.Headers["X-Mailer"] = "ERPStore.DKIMEmailerService";
			}
			var htmlView = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
			htmlView.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
			message.AlternateViews.Add(htmlView);

			base.Send(message);
		}

		public void AddDkimHeader(System.Net.Mail.MailMessage message)
		{
			var key = ERPStore.Configuration.ConfigurationSettings.AppSettings["dkimPrivateKey"];
			var domainKey = ERPStore.Configuration.ConfigurationSettings.AppSettings["dkimDomain"];
			var selector = ERPStore.Configuration.ConfigurationSettings.AppSettings["dkimSelector"];
			if (message.From.Host == domainKey)
			{
				try
				{
					var privateKey = DKIM.PrivateKeySigner.Create(key);
					var headerToSign = new string[] { "From", "To", "Subject" };
					var domainKeySigner = new DKIM.DomainKeySigner(privateKey, domainKey, selector, headerToSign);

					message.DomainKeySign(domainKeySigner);

					var dkimSigner = new DkimSigner(privateKey, domainKey, selector, headerToSign);
					message.DkimSign(dkimSigner);
				}
				catch(Exception ex)
				{
					ex.Data.Add("privatekey", key);
					ex.Data.Add("domainkey", domainKey);
					ex.Data.Add("domainselector", selector);
					ex.Data.Add("from", message.From.Address);
					foreach (var emailTo in message.To)
					{
						ex.Data.Add(string.Format("to{0}", message.To.IndexOf(emailTo)), emailTo.Address);
					}
					ex.Data.Add("subject", message.Subject);
					base.Logger.Error(ex);
				}
			}
		}



	}
}
